{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting name2time.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile name2time.py\n",
    "#! /usr/bin/env python\n",
    "# -*- coding: utf-8 -*-\n",
    "import os\n",
    "import time\n",
    "import sys\n",
    "import shutil\n",
    "import exifread\n",
    "reload(sys)\n",
    "sys.setdefaultencoding('utf-8')\n",
    "\n",
    "# for hachoir metadata\n",
    "from hachoir_core.error import HachoirError\n",
    "from hachoir_core.cmd_line import unicodeFilename\n",
    "from hachoir_parser import createParser\n",
    "from hachoir_core.tools import makePrintable\n",
    "from hachoir_metadata import extractMetadata\n",
    "from hachoir_core.i18n import getTerminalCharset\n",
    "\n",
    "def get_exif_time(file_name):\n",
    "    FIELD = 'EXIF DateTimeOriginal'\n",
    "    fd = open(file_name, 'rb')\n",
    "    tags = exifread.process_file(fd)\n",
    "    fd.close()\n",
    "\n",
    "    if FIELD in tags:\n",
    "        ctime = str(tags[FIELD])\n",
    "        try:\n",
    "            exif_time = time.strftime(\"%Y_%m_%d_%H%M%S\", time.strptime(ctime[0:19], \"%Y:%m:%d %H:%M:%S\"))\n",
    "        except ValueError: # some exif use YYYY-MM-DD instead of YYYY:MM:DD\n",
    "            exif_time = time.strftime(\"%Y_%m_%d_%H%M%S\", time.strptime(ctime[0:19], \"%Y-%m-%d %H:%M:%S\"))\n",
    "        return exif_time\n",
    "\n",
    "    # return None if no exif original time\n",
    "    return None\n",
    "\n",
    "def get_hachoir_time(filename):\n",
    "   \n",
    "    filename,realname = unicodeFilename(filename), filename\n",
    "    parser = createParser(filename, realname)\n",
    "    if not parser:\n",
    "        #print \"Unable to parse file\"\n",
    "        return None\n",
    "#    try:\n",
    "    metadata = extractMetadata(parser)\n",
    "#    except HachoirError, err:\n",
    "        #print \"Metadata extraction error: %s\" % unicode(err)\n",
    "#        metadata = None\n",
    "    if not metadata:\n",
    "        #print \"Unable to extract metadata\"\n",
    "        return None\n",
    "\n",
    "    text = metadata.exportPlaintext()\n",
    "    charset = getTerminalCharset()\n",
    "    for line in text:\n",
    "        line = makePrintable(line, charset)\n",
    "        if line[:16] == \"- Creation date:\":\n",
    "            # there might be more than one \"Creation date\" in metadata\n",
    "            # and the date might be like 1904-xx-xx, which is obviously wrong\n",
    "            # so we need to find any \"Creation date\" later than 2000, then return\n",
    "            # otherwise, return None to let the fs mtime work\n",
    "            timestamp = time.mktime(time.strptime(line[17:36], \"%Y-%m-%d %H:%M:%S\"))\n",
    "            if timestamp > time.mktime(time.strptime(\"2000-01-01 01:01:01\", \"%Y-%m-%d %H:%M:%S\")):\n",
    "                hachoir_time = time.strftime(\"%Y_%m_%d_%H%M%S\",time.localtime(timestamp + 8*3600))\n",
    "                return hachoir_time\n",
    "\n",
    "    return None\n",
    "\n",
    "\n",
    "def get_fs_time(filename):\n",
    "    stat = os.stat(filename)\n",
    "    fs_time = time.strftime(\"%Y_%m_%d_%H%M%S\", time.localtime(stat.st_mtime))\n",
    "    return fs_time\n",
    "\n",
    "def change_name_to_time(orig_name, drill):\n",
    "\n",
    "    # switch to absolute path in any case\n",
    "    orig_name = os.path.abspath(orig_name)\n",
    "\n",
    "    base_name = os.path.basename(orig_name)\n",
    "    dir_name = os.path.dirname(orig_name)\n",
    "    ext_name = base_name.split('.')[-1]\n",
    "    # FIXME: in file name like \"aaa.bbb.jpg\", \"bbb\" will be abandoned\n",
    "    prefix_name = base_name.split('.')[0]\n",
    "\n",
    "    # exif time works first; if None, then hachoir metadata time; if None, then fs mtime\n",
    "    new_name = get_exif_time(orig_name)\n",
    "    if new_name == None:\n",
    "        new_name = get_hachoir_time(orig_name)\n",
    "        if new_name == None:\n",
    "            new_name = get_fs_time(orig_name)\n",
    "            if new_name == None:\n",
    "                new_name = prefix_name\n",
    "    \n",
    "    full_name = dir_name + \"/\" + new_name + \".\" + ext_name\n",
    "    # make sure no duplication of name\n",
    "    if full_name != orig_name: # this if is to avoid no-changing-name\n",
    "        repeat_time = 1\n",
    "        while os.path.exists(full_name):\n",
    "            full_name = dir_name + \"/\" + new_name + \"_\" + str(repeat_time) + '.' + ext_name\n",
    "            repeat_time += 1\n",
    "    \n",
    "\n",
    "    if drill:\n",
    "        print \"orig: \" + orig_name\n",
    "        print \"then: \" + full_name\n",
    "        print \"\"\n",
    "    else:\n",
    "        os.rename(orig_name, full_name)\n",
    "        #shutil.move(orig_name, full_name)\n",
    "\n",
    "    \n",
    "def sanity_check():\n",
    "    result = True\n",
    "    recursive = False\n",
    "    drill = False\n",
    "    target = None\n",
    "    \n",
    "    if len(sys.argv) > 4 or len(sys.argv) < 2:\n",
    "        return False, False, False, None\n",
    "    \n",
    "    for arg in sys.argv[1:]:\n",
    "        if arg == \"-r\":\n",
    "            recursive = True\n",
    "        elif arg == \"-n\":\n",
    "            drill = True\n",
    "        elif os.path.exists(arg):\n",
    "            target = arg\n",
    "        else:\n",
    "            result = False\n",
    "            \n",
    "    return result, recursive, drill, target\n",
    "    \n",
    "def print_usage():\n",
    "    print \"Usage:\"\n",
    "    print \"    name2time [OPTION] FILE    : change name of FILE\"\n",
    "    print \"    name2time [OPTION] DIR     : change name of all files in DIR\"\n",
    "    print \"OPTIONS:\"\n",
    "    print \"    -r  recursive\"\n",
    "    print \"    -n  no actual rename, just show the result\"\n",
    "    \n",
    "if __name__ == \"__main__\":\n",
    " \n",
    "    result, recursive, drill, target = sanity_check()\n",
    "    \n",
    "    if not result:\n",
    "        print_usage()\n",
    "        exit()\n",
    " \n",
    "    if os.path.isfile(target):\n",
    "        change_name_to_time(target, drill)\n",
    "    \n",
    "    if os.path.isdir(target):\n",
    "        if not recursive:\n",
    "            for ff in os.listdir(target):\n",
    "                if os.path.isfile(target + \"/\" + ff):\n",
    "                    change_name_to_time(target + \"/\" + ff, drill)\n",
    "        else: # if recursive\n",
    "            for home, dirs, files in os.walk(target):\n",
    "                for ff in files:\n",
    "                    change_name_to_time(home + \"/\" + ff, drill)\n",
    "                    \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting metadata.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile metadata.py\n",
    "#! /usr/bin/env python\n",
    "# -*- coding: utf-8 -*-\n",
    "import os\n",
    "import time\n",
    "import sys\n",
    "import exifread\n",
    "reload(sys)\n",
    "sys.setdefaultencoding('utf-8')\n",
    "\n",
    "from hachoir_core.error import HachoirError\n",
    "from hachoir_core.cmd_line import unicodeFilename\n",
    "from hachoir_parser import createParser\n",
    "from hachoir_core.tools import makePrintable\n",
    "from hachoir_metadata import extractMetadata\n",
    "from hachoir_core.i18n import getTerminalCharset\n",
    "\n",
    "# Get metadata for video file\n",
    "def hachoir_metadata(filename):\n",
    "    filename,realname = unicodeFilename(filename), filename\n",
    "    parser = createParser(filename, realname)\n",
    "    if not parser:\n",
    "        print \"Unable to parse file\"\n",
    "        return None\n",
    "    try:\n",
    "        metadata = extractMetadata(parser)\n",
    "    except HachoirError, err:\n",
    "        print \"Metadata extraction error: %s\" % unicode(err)\n",
    "        metadata = None\n",
    "    if not metadata:\n",
    "        print \"Unable to extract metadata\"\n",
    "        return None\n",
    "\n",
    "    text = metadata.exportPlaintext()\n",
    "    charset = getTerminalCharset()\n",
    "    for line in text:\n",
    "        print makePrintable(line, charset)\n",
    "\n",
    "    return metadata\n",
    "\n",
    "def exif_metadata(file_name):\n",
    "\n",
    "    FIELDS = ('EXIF DateTimeOriginal',)\n",
    "\n",
    "    print \"EXIF Metadata:\"\n",
    "    \n",
    "    fd = open(file_name, 'rb')\n",
    "    tags = exifread.process_file(fd)\n",
    "    fd.close()\n",
    "\n",
    "    for field in FIELDS:\n",
    "        if field in tags:\n",
    "            print \"- \" + field + \": \" + str(tags[field])\n",
    "\n",
    "def fs_meta(filename):\n",
    "\n",
    "    print \"FS Metadata:\"\n",
    "    stat = os.stat(pathname)\n",
    "    print \"- Create Time: \" + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(stat.st_ctime))\n",
    "    print \"- Modify Time: \" + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(stat.st_mtime))\n",
    "    print \"- Access Time: \" + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(stat.st_atime))\n",
    "    \n",
    "def sanity_check():\n",
    "    if len(sys.argv) != 2:\n",
    "        return False\n",
    "        \n",
    "    if not os.path.exists(sys.argv[1]):\n",
    "        return False\n",
    "\n",
    "    return True\n",
    "    \n",
    "def print_usage():\n",
    "    print \"Usage:\"\n",
    "    print \"    metadata.py FILE    : show metadata of FILE\"\n",
    "    \n",
    "if __name__ == \"__main__\":\n",
    "    \n",
    "    if not sanity_check():\n",
    "        print_usage()\n",
    "        exit(1)\n",
    "        \n",
    "    pathname = sys.argv[1]\n",
    "    hachoir_metadata(pathname)\n",
    "    exif_metadata(pathname)\n",
    "    fs_meta(pathname)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing timestring_transfer.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile timestring_transfer.py\n",
    "\n",
    "import os\n",
    "import time\n",
    "\n",
    "target_dir = \"/media/jimzeus/回忆/My Documents/__ok/拍摄设备/MB525/\"\n",
    "\n",
    "for f in os.listdir(target_dir):\n",
    "    basename = os.path.basename(f)\n",
    "    ext_name = basename.split('.')[-1]\n",
    "\n",
    "    print target_dir + basename\n",
    "    afterbase = time.strftime(\"%Y_%m_%d_%H%M%S\", time.strptime(basename[0:19], \"%Y-%m-%d_%H-%M-%S\"))\n",
    "    aftername = target_dir + afterbase + '.' + ext_name\n",
    "    os.rename(target_dir+basename, aftername) \n",
    "    print \"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
